package com.boat.hbase.util;

import javax.annotation.PreDestroy;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Description: 获取hbase连接，单例
 * @author boat
 * @date 2017年12月27日 上午9:22:00
 * @version V1.0
 */

@Component("hbaseConectionManager")
public class HbaseConectionManager {

	private volatile Connection connection;

	@Value("${hadoop.zk.host}")
	private String zookeeperHost;

	@Value("${hadoop.zk.client-port}")
	private String zookeeperClientPort;

	/**
	 * 获取hbase连接，单例
	 * 
	 * @return
	 * @throws Exception
	 */
	public Connection getConnection() throws Exception {
		if (connection == null) {
			synchronized (this) {
				Configuration hbaseConfiguration = new Configuration();
				hbaseConfiguration.set("hbase.zookeeper.quorum", zookeeperHost);
				hbaseConfiguration.set("hbase.zookeeper.property.clientPort", zookeeperClientPort);
				if (connection != null) {
					if (!connection.isClosed() && !connection.isAborted()) {
						return connection;
					}
				}
				if (connection != null) {
					connection.close();
				}
				connection = ConnectionFactory.createConnection(hbaseConfiguration);
				return connection;
			}
		}
		return connection;
	}

	/**
	 * 销毁hbase连接，容器销毁前销毁
	 */
	@PreDestroy
	public void destroy() {
		if (connection != null) {
			try {
				connection.close();
			} catch (Exception e) {

			}
		}
	}

}